package com.rutas.java;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


public class Tab2 extends ListActivity{
	 
	private static final int OPTION_BUSCAR = Menu.FIRST;
	private static final int OPTION_ORDENAR = Menu.FIRST + 1;
	private BaseDatos bdTab2;
	public String[] listaDatos;
	public int[] distancias;
	
//---------------------------------- Subclases necesarias --------------------------------------------------------------------
	//Almacena los IDs de cada componente
	public class ViewWrapper{
		View base;
		TextView label;
		ImageView icon;
		ImageView arrow;
		
		public ViewWrapper(View base){
			this.base = base;
		}
		
		public TextView getLabel(){
			if (label == null)
				label = (TextView)base.findViewById(R.id.texto);
			return label;
		}
		
		public ImageView getIcon(){
			if (icon == null)
				icon = (ImageView)base.findViewById(R.id.icono);
			return icon;
		}
		public ImageView getArrow(){
			if (arrow == null)
				arrow = (ImageView)base.findViewById(R.id.arrow);
			return arrow;
		}
	} 
	
	public class MiAdaptador extends ArrayAdapter<String>{
		Context contexto;

		public MiAdaptador(Context context) {
			super(context, R.layout.fila_list, listaDatos);
			contexto = context;
		}		
		@Override
		public View getView (int position, View convertView, ViewGroup parent){
			//Aprovechamos convertView para no crear nueva fila
			View fila = convertView;
			ViewWrapper envoltorio = null;
			
			if (fila == null){
				fila = View.inflate(this.contexto, R.layout.fila_list, null);
				envoltorio = new ViewWrapper(fila);
				fila.setTag(envoltorio);
			}else
				envoltorio = (ViewWrapper)fila.getTag();
			
			TextView label = envoltorio.getLabel();			
			label.setText(listaDatos[position]);
			
			
			ImageView iconito = envoltorio.getIcon();
			iconito.setImageResource(setIcono(distancias[position]));
			ImageView flecha = envoltorio.getArrow();
			flecha.setImageResource(R.drawable.monotone_arrow_right);
			return fila;
		}
	}
//-------------------------Metodos-----------------------------------------------------------
	
	private void switchTab(String cadena){
		Welcome padre = (Welcome)getParent();
		padre.setNombre(cadena);
		padre.switchTab(0);	//Cambiamos de tabulador
	}
	
	public int setIcono(int distancia){
		int miIcono;
		if (distancia > 50){
			miIcono = R.drawable.flag_red_32;
		}else if (distancia < 10){
			miIcono = R.drawable.flag_green_32;
		}else
			miIcono = R.drawable.flag_yellow_32;
		return miIcono;
	}
	
/*	private void mostrarListView(String[] lista){
		//setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lista));	

	}*/
	
	//Metodo que devuelve la posicion de un valor dentro de un string
	private int buscar(String[] lista, String texto){
		int i = 0;
		boolean encontrado = false;
		int tam = lista.length;
		while ((i < tam) && (!encontrado)) {			
			if (lista[i].toLowerCase().contains(texto.toLowerCase()))
				encontrado = true;
			else
				i++;
		}
		if (!encontrado)
			i = -1;
		return i;
	}
//------------------------------Override----------------------------------------------------------------
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.own_listview);
 
        bdTab2 = new BaseDatos(this);
        try {        	 
     		bdTab2.abrirBD();   
     	}catch(SQLException sqle){     
     		throw sqle;
     	}
        Cursor c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "nombre ASC");
        listaDatos = new String[c.getCount()];
        distancias = new int[c.getCount()];
        int i = 0;
        while (c.moveToNext()){
        	listaDatos[i] = c.getString(0);
        	distancias[i] = c.getInt(1);
        	i++;
        }
        c.close();
        
        setListAdapter(new MiAdaptador(Tab2.this));
        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> l, View v, int pos, long id) {
				switchTab(listaDatos[pos]);
				return true;
			}    	
		});
        Toast.makeText(this,""+listaDatos.length + " "+ this.getString(R.string.senderos), Toast.LENGTH_LONG).show();
    }
	
	@Override
	protected void onListItemClick(ListView l,View v, int position, long id){
		//Extraemos la informacion del sendero dado
		String[] informacion = bdTab2.getInformacion(listaDatos[position]);	
        
		Intent i = new Intent(Tab2.this, info.class);
		i.putExtra("informacion", informacion);
		i.putExtra("ActivityName", "Tab2");
		startActivityForResult(i,0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if ((requestCode == 0) && (resultCode == Activity.RESULT_CANCELED)){
			String nombre = data.getCharSequenceExtra("sendero").toString();
			switchTab(nombre);	//cambia de tabulador
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id){
		switch(id){
		case OPTION_BUSCAR:
			LayoutInflater ventana = LayoutInflater.from(this);
			final View busqueda = ventana.inflate(R.layout.dialog_buscar, null);
			final EditText etBuscar = (EditText) busqueda.findViewById(R.id.etDialogBuscar);
			return new AlertDialog.Builder(Tab2.this)
					.setView(busqueda)
					.setTitle(R.string.introduce_sendero)
					.setIcon(android.R.drawable.ic_search_category_default)
					.setPositiveButton(R.string.buscar, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (!etBuscar.getText().toString().equals("")){
								int pos = buscar(listaDatos, etBuscar.getText().toString().trim());
								etBuscar.setText("");
								if (pos != -1){
									setSelection(pos);	//coloca el cursor en la posicion pos
								}
								else
									Toast.makeText(Tab2.this, R.string.not_found, Toast.LENGTH_SHORT).show();
						}}
					})
					.setNegativeButton(R.string.volver, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//No hacemos nada
							etBuscar.setText("");
						}
					})
					.create();
		case OPTION_ORDENAR:
			LayoutInflater ventanaOrdenar = LayoutInflater.from(this);
			final View ordenar = ventanaOrdenar.inflate(R.layout.dialog_ordenar, null);

			return new AlertDialog.Builder(Tab2.this)
			.setView(ordenar)
			.setTitle(R.string.ordenar_lista)
			.setPositiveButton(R.string.ordenar, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					RadioGroup rdGCampo = (RadioGroup) ordenar.findViewById(R.id.RadioGroupCampo);
					RadioGroup rdGSentido = (RadioGroup) ordenar.findViewById(R.id.RadioGroupSentido);
					Cursor c = null;
					switch (rdGCampo.getCheckedRadioButtonId()){
					case R.id.radio_nombre:
						//Si es sentido ascendente
						if (rdGSentido.getCheckedRadioButtonId() == R.id.radio_Asc)
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "nombre ASC");
						else
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "nombre DESC");
						break;
					case R.id.radio_durac:
						if (rdGSentido.getCheckedRadioButtonId() == R.id.radio_Asc)
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "duracion ASC");
						else
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "duracion DESC");
						break;
					case R.id.radio_long:
						if (rdGSentido.getCheckedRadioButtonId() == R.id.radio_Asc)
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "longitud ASC");
						else
							c = bdTab2.getInfoMap(false, new String[]{"nombre", "longitud"}, null, null, null, null, "longitud DESC");
						break;
					}
					int i = 0;
			        while (c.moveToNext()){
			        	listaDatos[i] = c.getString(0);
			        	distancias[i] = c.getInt(1);
			        	i++;
			        }
			        c.close();
			        setListAdapter(new MiAdaptador(Tab2.this));
				}
			}).setNegativeButton(R.string.volver, new DialogInterface.OnClickListener(){
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// No hacer nada
				}
			})
			.create();
		}
		return null;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu opciones){
		opciones.add(0, OPTION_BUSCAR, 0, R.string.buscar).setIcon(android.R.drawable.ic_menu_search);
		opciones.add(0, OPTION_ORDENAR, 0, R.string.ordenar).setIcon(android.R.drawable.ic_menu_sort_alphabetically);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem opcion){
		switch(opcion.getItemId()){
			case OPTION_BUSCAR:
				showDialog(OPTION_BUSCAR);
				break;
			case OPTION_ORDENAR:
				showDialog(OPTION_ORDENAR);
				break;
		}
		return super.onOptionsItemSelected(opcion);
	}
	
	@Override
	protected void onDestroy(){
		bdTab2.close();
    	super.onDestroy();
    		//bdTab2.cerrarBd();
    }
}